package com.javaforever.clocksimplejee4.serviceimpl;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import com.baidu.ai.aip.utils.Base64Util;
import com.baidu.ai.aip.utils.FileUtil;
import com.baidu.aip.face.AipFace;
import com.javaforever.clocksimplejee4.domain.User;

public class FaceServiceImpl {
	protected static final String APP_ID = "10563166";
	protected static final String API_KEY = "AN8XVeY2E7kFacHH03PdIQXc";
	protected static final String SECRET_KEY = "YaeEpYMGvkghZpViYadVsRU38pmWt8kF";
	protected static final int proxy_port = 80;
	protected static AipFace client;
	
	public FaceServiceImpl() {
		super();
		client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        //client.setHttpProxy("10.221.61.196", proxy_port);  // 设置http代理
	}
	
	// protected static boolean serverConnected() {
	// try {
	// String json =
	// HttpUtil.post("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=AN8XVeY2E7kFacHH03PdIQXc&client_secret=YaeEpYMGvkghZpViYadVsRU38pmWt8kF",null,null);
	// System.out.println("JerryDebug:"+json);
	// String accessToken =
	// ((JSONObject)JSONObject.stringToValue(json)).getString("access_token");
	// if (!StringUtil.isBlank(accessToken)) return true;
	// else return false;
	// }catch (Exception e) {
	// //e.printStackTrace();
	// return false;
	// }
	// }
	
    public User recogFace(String faceUserGroupId, byte[] imagedata) {
        try {     
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("ext_fields", "faceliveness");
            options.put("user_top_num", "1");
            
            JSONObject result = client.identifyUser(faceUserGroupId,imagedata,options);
            System.out.print("JerryDebug:faceRecog:"+result.toString());
            if (result!=null) {
            	Double score = ((JSONObject)result.getJSONArray("result").get(0)).getJSONArray("scores").getDouble(0);
            	if (score >=78) {
            		String faceUid =  ((JSONObject)result.getJSONArray("result").get(0)).getString("uid");
            		
            		User u = new User();
            		u.setFaceUid(faceUid);
            		u.setScore(score);
            		return u;
            	}
            	User u = new User();
            	u.setScore(score);
            	return u;
            }
            else
            	return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public Boolean addUserFace(String faceUserGroupId, byte[] imagedata, User user) {
        try {     
            HashMap<String,String> options = new HashMap<String,String>();
            options.put("action_type","append");
            
            JSONObject result = client.addUser(user.getFaceUid(), user.getFullName(), User.FACE_USER_GROUP, imagedata, options);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean removeUserFace(String faceUserGroupId, String uid) {
        try {     
        	HashMap<String, String> options = new HashMap<String, String>();
            options.put("group_id", faceUserGroupId);

            JSONObject result = client.deleteUser(uid, options);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean detectOneValidFace(byte[] imagedata) {
    	boolean success = false;
    	HashMap<String, String> options = new HashMap<String, String>();
    	options.put("max_face_num", "3");
    	options.put("face_fields","qualities");
    	
    	JSONObject result = client.detect(imagedata, options);
    	System.out.println(result.toString());
    	if (result!=null) {
        	if (result.getInt("result_num")==1) {
        		success = true;
        	}
        	else {
        		success = false;
        	}
        }    	
    	return success;
    }
    
    public List<User> listAllFaces() {
    	boolean success = false;
    	HashMap<String, String> options = new HashMap<String, String>();
    	
    	JSONObject result = client.getGroupUsers(User.FACE_USER_GROUP, options);
    	System.out.println(result);
    	List<User> users = new ArrayList<User>();
    	for(int i=0;i<result.getJSONArray("result").length();i++) {
    		User u = new User();
    		JSONObject jo = (JSONObject)result.getJSONArray("result").get(i);
    		u.setFaceUid(jo.getString("uid"));
    		String fullname = jo.getString("user_info");
    		String [] names = fullname.split(" ");
    		if (names.length >= 2) {
    			u.setFirstname(names[0]);
    			u.setLastname(names[1]);
    		}else if(names.length == 1) {
    			u.setFirstname(names[0]);
    		}
    		users.add(u);
    	}
    	return users;
    }
    
    public static void main(String [] args) throws Exception{
    	
//    	// 本地文件路径
//    	 String filePath = "D:\\JerryWorkspace\\FaceRecog\\res\\b1.jpg";
//         byte[] imgData = FileUtil.readFileByBytes(filePath);
//         String imgStr = Base64Util.encode(imgData);
//         String imgParam = URLEncoder.encode(imgStr, "UTF-8");
//         
//         User u = new User();
//         u.setUsername("bill");
//         u.setFirstname("Bill");
//         u.setLastname("Gates");
//         u.setFaceUid(u.getUsername());
//         
//     	// 本地文件路径
//    	 String filePath2 = "D:\\JerryWorkspace\\FaceRecog\\res\\j1.jpg";
//         byte[] imgData2 = FileUtil.readFileByBytes(filePath2);
//         String imgStr2 = Base64Util.encode(imgData2);
//         String imgParam2 = URLEncoder.encode(imgStr2, "UTF-8");
//         
//      // 本地文件路径
//    	 String filePath3 = "D:\\JerryWorkspace\\FaceRecog\\res\\text1.jpg";
//         byte[] imgData3 = FileUtil.readFileByBytes(filePath3);
//         String imgStr3 = Base64Util.encode(imgData3);
////         System.out.println(imgStr3);
////         System.out.println("===================");
//         String imgParam3 = URLEncoder.encode(imgStr3, "UTF-8");
//         
//      // 本地文件路径
//    	 String filePath4 = "D:\\JerryWorkspace\\FaceRecog\\res\\j2.jpg";
//         byte[] imgData4 = FileUtil.readFileByBytes(filePath4);
//         String imgStr4 = Base64Util.encode(imgData4);
//         
//         String imgParam4 = URLEncoder.encode(imgStr4, "UTF-8");
//       System.out.println(imgStr4);
//       System.out.println("===================");
//         User u2 = new User();
//         u2.setUsername("steven");
//         u2.setFirstname("Steven");
//         u2.setLastname("Jobs");
//         u2.setFaceUid(u2.getUsername());
        
        FaceServiceImpl fimpl= new FaceServiceImpl();
        fimpl.listAllFaces();
//        boolean success = fimpl.detectOneValidFace(imgData3);
//        System.out.println("-----------------");
//        System.out.println(success);
//        fimpl.addUserFace(User.FACE_USER_GROUP, imgData, u);
//        fimpl.addUserFace(User.FACE_USER_GROUP, imgData2, u2);
//        
//        String uid1 = fimpl.recogFace(User.FACE_USER_GROUP, imgData3);
//        String uid2 = fimpl.recogFace(User.FACE_USER_GROUP, imgData4);
//        System.out.println(uid1);
//        System.out.println(uid2);
//        //fimpl.removeUserFace(User.FACE_USER_GROUP, u.getFaceUid());
//    	System.out.println(FaceServiceImpl.serverConnected());
    }
}

